package com.uziot.bucket.poi.text;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.LinkedList;
import java.util.Scanner;

/**
 * @author shidt
 * @version V1.0
 * @className ReadFileLine
 * @date 2020-11-14 22:31:37
 * @description 按照行读取文件并返回文件行的list
 */
@Slf4j
@Service
public class ReadFileLineService {

    public LinkedList<String> readFileLines(String filePath) {
        return readFileLines(new File(filePath));
    }

    /**
     * 按照行读取文件并存储到List
     *
     * @param file file
     * @return list
     */
    public LinkedList<String> readFileLines(File file) {
        LinkedList<String> fileList = new LinkedList<>();
        if (!file.exists()) {
            throw new RuntimeException("没有找到对应的文件！");
        }
        log.info("开始读取文件....");
        try {
            InputStream is = new FileInputStream(file);
            Scanner scan = new Scanner(is, "UTF-8");
            while (scan.hasNextLine()) {
                String line = scan.nextLine();
                if (null != line && !"".equals(line.trim())) {
                    fileList.offer(line.trim());
                }
            }
            is.close();
            scan.close();
            log.info("文件读取完成....");
        } catch (IOException e) {
            throw new RuntimeException("读取文件发生异常，具体信息为：" + e);
        }
        return fileList;
    }
}
